package com.iflyun.LogsCustmerToHDFS.listener;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.iflyun.LogsCustmerToHDFS.entity.WeChatLog;

import com.iflyun.LogsCustmerToHDFS.service.WeChatLogService;




/**
 * 
 * @ClassName:  WeChatLogListener   
 * @Description:微信队列监听器   
 * @author: wenquxing  
 * @date:   2017年8月25日 下午1:17:51   
 *
 */
public class WeChatLogListener implements  MessageListener {
	
	private static final Logger logger = LoggerFactory.getLogger(WeChatLogListener.class);
	
	private List<WeChatLog> list =new ArrayList<WeChatLog>();
	
	private String fileName="";
	
	private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	

	@Autowired
	private WeChatLogService weChatLogService;
	
	
	@Override
	public void onMessage(Message message) { 
		String json="";
		WeChatLog weChatlog=null;
		Date date=null;
		Date date1=null;
		Date date2=null;
		String tsStr="";
		try {
			json=new String(message.getBody(), "UTF-8");
			weChatlog = JSON.parseObject(json, WeChatLog.class);
			if("".equals(fileName)) {
				date=new Date();
				fileName=sdf.format(date);
			}else {
				try {
//					date= sdfSecond.parse(weblog.getAccessTime());
					tsStr = sdf.format(weChatlog.getAccessTime());		
					date1 = sdf.parse(tsStr); //数据时间
					date2=sdf.parse(fileName);//当前目录时间
				} catch (ParseException e) {
					e.printStackTrace();
				}
				if(date1.getTime()>date2.getTime()) {
					list=weChatLogService.setWeChatLogList(list,fileName);
					fileName=tsStr;				
				}else if(date1.getTime()<date2.getTime()) {
					logger.error("数据时间小于当前目录时间:"+weChatlog.getId());
					return ;
				}
				
			}
			list.add(weChatlog);
			
		} catch (UnsupportedEncodingException e) {
			logger.error("json转换失败:",e);
		}
		
		if(list.size()>=1000){
			list=weChatLogService.setWeChatLogList(list,fileName);
		}
	
    }

}